<template>
	<view class="wrap">
		<view class="search-bar">
			<view class="search-bar-inp">
				<input v-model.trim="keywords" placeholder="搜索零部件" placeholder-style="color:#ccc" type="text" value=""
					confirm-type="search" @confirm="search" :focus="focusState" @blur="focusState = false" />
				<view class="marginR" v-if="keywords" @click="searchClear">
					<uni-icons size="16" color="#999999" type="clear"></uni-icons>
				</view>
				<view class="btn" @click="search" v-else>
					<uni-icons size="22" color="#0091ff" type="search"></uni-icons>
				</view>
			</view>
		</view>
		<memberTree :keywords="keywords" :isSearch="isSearch" :tree="data" :expandedIds="expandedIds"
			:defaultId="defaultId" @node-click="nodeClick" v-if="data.length">
		</memberTree>
		<view class="empty" v-else>
			<view class="circle">
				<image src="@/static/images/seachEmpty.png"></image>
			</view>
			<view class="title"> 暂无搜索结果 </view>
		</view>
		<view class="bottom-block"> </view>
		<view class="item_botm" @click="imTasksClick">
			<view :class="[isState ? 'botm' : 'botm botmbg']">{{ isFlag && flagList.length ? '选择层站' : '确定' }}</view>
		</view>
		<uni-popup ref="popup" type="bottom">
			<view class="flag">
				<view class="line"><text></text></view>
				<view class="flagTitle">
					选择层站</view>
				<view class="flagContent">
					<memberTree :tree="flagList" @node-click="nodeClickFlag" :isFlag="true">
					</memberTree>
					<view class="empty"></view>
				</view>
				<view class="item_botm" @click="imTasksClickFlag">
					<view :class="[isStateFlag ? 'botm' : 'botm botmbg']">确定</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import memberTree from '@/components/member-tree/tree-nodesE.vue';
import { getTree, getTreeNew, getTemplateTree, getTemplateTreeList } from '@/apis/elevator.js';
import { hanleToken } from '@/utils/utils.js';
export default {
	components: { memberTree },
	data() {
		return {
			keywords: '',
			tree: [],
			data: [],
			slect: {}, // 勾选的数据
			expandedIds: [], // 用于点击打开子级
			form: {},
			isSearch: false,
			defaultId: '',
			elevatorId: "",
			isFlag: false,
			flagList: [],
			flag: {},
		};
	},
	onLoad(os) {
		console.log(os, 'os的值');
		if (Object.keys(os).length) {
			let res = JSON.parse(os.partMsg);
			if (res.expandedIds) {
				this.expandedIds = res.expandedIds;
			}
			if (os.elevatorId) {
				this.elevatorId = os.elevatorId
			}
			this.searchFuc();
		} else {
			this.searchFuc();
		}
	},
	computed: {
		isState() {
			return this.slect.name ? true : false;
		},
		isStateFlag() {
			return this.flag.name ? true : false;
		},
	},
	methods: {
		// 清空搜索
		searchClear() {
			this.keywords = '';
			this.expandedIds = [];
			this.searchFuc();
			this.$nextTick(() => {
				this.focusState = true;
			});
		},
		search() {
			if (this.keywords == '') {
				this.expandedIds = [];
			}
			this.searchFuc();
		},
		// 搜索
		searchFuc(val) {
			if (this.keywords) {
				this.isSearch = true;
				let mhres = this.filterNodeMethod(this.keywords, this.tree);
				this.data = JSON.parse(JSON.stringify(mhres));
				return;
			}
			uni.showLoading({
				title: '加载中',
				mask: true,
			});
			getTreeNew({
				name: this.keywords,
				elevatorId: this.elevatorId
			}).then((res) => {
				if (res.data.length == 0) {
					getTree({
						name: this.keywords,
					}).then((res) => {
						if (res.data.length && this.keywords == '') {
							res.data.unshift({
								name: '整梯',
								id: '0',
							});
						}
						this.tree = res.data.map((item, index) => {
							if (index == 1) {
								this.defaultId = item.id;
							}
							item.isOpen = false;
							return item;
						});
						this.isSearch = false;
						this.data = JSON.parse(JSON.stringify(this.tree));
						uni.hideLoading();
						return;
					});
				}
				if (res.data.length && this.keywords == '') {
					res.data.unshift({
						name: '整梯',
						id: '0',
					});
				}
				this.tree = res.data.map((item, index) => {
					if (index == 1) {
						this.defaultId = item.id; // 默认展开第一级
					}
					item.isOpen = false;
					return item;
				});
				this.isSearch = false;
				this.data = JSON.parse(JSON.stringify(this.tree));
				uni.hideLoading();
			});
		},
		// 点击每一项
		nodeClick(res) {
			this.slect.isOpen = false; // 取消上一项的选中
			this.$forceUpdate();
			if (res.flag == 2) {
				getTemplateTree({
					elevatorId: this.elevatorId,
					flag: res.flag,
					partsId: res.id
				}).then(res => {
					this.flagList = res.data.map(item => {
						item.name = item.name + '层';
						return item;
					});
				})
				this.isFlag = true;
			} else if (res.flag == 1) {
				getTemplateTreeList({
					elevatorId: this.elevatorId,
					flag: res.flag,
					partsId: res.id
				}).then(res => {
					res.data.forEach(item => {
						if (item.flag == 1) {
							item.name = item.name + '层'
						}
					})
					this.flagList = res.data.filter(item => item.flag == 1);
				})
				this.isFlag = true;
			} else {
				this.isFlag = false;
			}
			if (res.isOpen) {
				this.slect = res;
			} else {
				this.slect = {};
			}
		},
		// 点击层站任一级
		nodeClickFlag(res) {
			this.flag.isOpen = false; // 取消上一项的选中
			if (res.isOpen) {
				this.flag = res;
			} else {
				this.flag = {};
			}
		},
		// 分配任务
		imTasksClick() {
			if (this.isFlag && this.flagList.length) {
				this.$refs.popup.open()
				return
			}
			if (this.slect.name) {
				let arr = [];
				this.findParent(this.data, this.slect, arr);
				this.slect.routeNmae = arr.map((item) => item.name).join('>');
				this.slect.topName = arr[0].name;
				if (
					this.slect.routeNmae.indexOf('井道及底坑') != -1 &&
					arr.length > 1
				) {
					this.slect.topName = arr[1].name;
				}
				this.slect.expandedIds = arr.map((item) => item.id);
				hanleToken('set', 'componentSelect', this.slect);
				uni.navigateBack({
					delta: 1,
				});
			}
		},
		imTasksClickFlag() {
			if (this.flag.name) {
				let arr = [];
				this.findParent(this.data, this.slect, arr);
				this.slect.routeNmae = arr.map((item) => item.name).join('>');
				this.slect.topName = arr[0].name;
				if (
					this.slect.routeNmae.indexOf('井道及底坑') != -1 &&
					arr.length > 1
				) {
					this.slect.topName = arr[1].name;
				}
				this.slect.expandedIds = arr.map((item) => item.id);

				this.$refs.popup.close();
				let arr2 = [];
				this.findParent(this.flagList, this.flag, arr2);
				this.flag.routeNmae = arr2.map((item) => item.name).join('>');
				this.flag.topName = arr2[0].name;
				if (
					this.flag.routeNmae.indexOf('井道及底坑') != -1 &&
					arr2.length > 1
				) {
					this.flag.topName = arr2[1].name;
				}
				this.flag.expandedIds = arr2.map((item) => item.id);
				hanleToken('set', 'templateSelect', { slect: this.slect, flag: this.flag });
				uni.navigateBack({
					delta: 1,
				});
			}
		},
		findParent(data, target, result) {
			for (let item of data) {
				console.log()
				if (item.id === target.id) {
					// 将查找到的目标数据加入结果数组中
					result.unshift(item);
					return true;
				}
				if (item.children && item.children.length > 0) {
					// 根据查找到的结果往上找父级节点
					let isFind = this.findParent(item.children, target, result);
					if (isFind) {
						result.unshift(item);
						return true;
					}
				}
			}
			return false;
		},
		filterNodeMethod(value, arr) {
			if (!arr) {
				return [];
			}
			let newarr = [];
			arr.forEach((element) => {
				if (element.name.indexOf(value) > -1) {
					const ab = this.filterNodeMethod(value, element.children);
					const obj = {
						...element,
						children: ab,
					};
					this.expandedIds.push(obj.id); // 记录需要展开搜素到的选项
					newarr.push(obj);
				} else {
					if (element.children && element.children.length > 0) {
						const ab = this.filterNodeMethod(value, element.children);
						const obj = {
							...element,
							children: ab,
						};
						if (ab && ab.length > 0) {
							this.expandedIds.push(obj.id); // 记录需要展开搜素到的选项
							newarr.push(obj);
						}
					}
				}
			});
			return newarr;
		},
		// 关键词过滤
		filterTree(nodes, query) {
			// 条件就是节点的title过滤关键字
			let predicate = function (node) {
				// let strs = ''
				// if(node && node.title){
				// 	const reg = new RegExp(query,'g');
				// 	strs = node.title.replace(reg,`<text style="color: yellow">${query}</text>`)
				// 	console.log("进来了，，，",node,query,strs)
				// }
				return node.title.includes(query);
			};

			// 结束递归的条件
			if (!(nodes && nodes.length)) {
				return [];
			}
			let newChildren = [];
			for (let node of nodes) {
				if (node.children && node.children.length) {
					node.show = true;
				}

				// 一、带父节点     以下两个条件任何一个成立，当前节点都应该加入到新子节点集中
				// 1. 子孙节点中存在符合条件的，即 subs 数组中有值
				// 2. 自己本身符合条件
				let subs = this.filterTree(node.children, query);

				if (predicate(node)) {
					newChildren.push(node);
				} else if (subs && subs.length) {
					node.children = subs;
					newChildren.push(node);
					this.expandedIds.push(node.id);
				}

				// 二、不带父节点     以下只需要考虑自身的节点满足条件即可,不用带上父节点
				// if (predicate(node)) {
				// 	newChildren.push(node);
				// 	node.children = this.filterTree(node.children, query);
				// } else {
				// 	newChildren.push(...this.filterTree(node.children, query));
				// }
			}
			return newChildren.length ? newChildren : [];
		},
	},
};
</script>

<style lang="scss" scoped>
page {
	background-color: #f6f6f6;
	color: #333;
	width: 100%;
}

.empty {
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	width: 100%;
	height: 300rpx;

	.circle {
		width: 64rpx;
		height: 64rpx;
	}

	image {
		width: 64rpx;
		height: 64rpx;
	}

	.title {
		font-size: 26rpx;
		color: #999;
		font-weight: 400;
		margin-top: 10rpx;
	}
}

.wrap {
	background-color: #f6f6f6;
	width: 100%;
	min-height: 100vh;

	.item_botm {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		z-index: 99;
		background-color: #ffffff;
		padding: 0 20rpx 0rpx 20rpx;
		height: 98rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		border-top: 1rpx #eee solid;

		.botm {
			width: 720rpx;
			margin: 0 auto;
			height: 70rpx;
			background: #0091ff;
			border-radius: 8rpx;
			line-height: 70rpx;
			text-align: center;
			font-size: 28rpx;
			font-weight: 500;
			color: #ffffff;
		}

		.botmbg {
			background: #efefef;
			color: #cccccc;
		}
	}
}

.bottom-block {
	width: 100%;
	height: 240rpx;
}

.search-bar {
	background-color: #fff;
	width: 100%;
	margin-bottom: 16rpx;
	display: flex;

	.search-bar-inp {
		width: 710rpx;
		margin: 24rpx auto;
		background-color: #f6f6f6;
		border-radius: 8rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;

		.marginR {
			margin-right: 20rpx;
		}

		input {
			font-size: 26rpx;
			flex: 1;
			padding: 12rpx 28rpx;
		}

		.btn {
			width: 90rpx;
			text-align: center;
			height: auto;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}
}

.flag {
	background: #ffffff;
	border-radius: 8rpx;
	box-sizing: border-box;
	box-shadow: 0px 0px 8rpx 0px rgba(0, 0, 0, 0.2);
	max-height: 80vh;
	padding-top: 20rpx;

	.flagTitle {
		color: #333;
		font-weight: 500;
		font-size: 32rpx;
		padding-left: 20rpx;
		padding-bottom: 20rpx;
		border-bottom: 2rpx solid #eee;
	}

	.flagContent {
		background: #f6f6f6;

		.empty {
			height: 110rpx;
		}
	}

	.line {
		display: flex;
		justify-content: center;

		text {
			width: 64rpx;
			height: 10rpx;
			background: #d8d8d8;
			border-radius: 6rpx;
		}
	}
}
</style>
